#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/7/12 18:26
# @File    : 贝塞尔DEV.py
# @Description : -i http://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn


import tkinter as tk






def on_mouse_down(event):
    global t2_xy
    t2_xy = (event.x, event.y)



def on_mouse_up(event):
    # 鼠标抬起
    global canvas, t1_xy
    start_x, start_y = t1_xy
    end_x, end_y = (event.x, event.y)
    canvas.create_line(start_x, start_y, end_x, end_y, fill="black", width=2)


def on_mouse_move(event):
    # 鼠标移动
    global canvas, t1_xy, t2_xy
    start_x, start_y = t1_xy
    end_x, end_y = (event.x, event.y)
    canvas.delete("current_line")
    canvas.create_line(start_x, start_y, end_x, end_y, tags="current_line", fill="black", width=2)

    delta_x = event.x - t2_xy[0]
    delta_y = event.y - t2_xy[1]
    x = t1.winfo_x() + delta_x
    y = t1.winfo_y() + delta_y
    print(event.x, event.y)
    print("-------------------")
    parent_width = canvas.master.winfo_width()
    parent_height = canvas.master.winfo_height()
    current_frame_width = t1.winfo_width()
    current_frame_height = t1.winfo_height()
    print(f"current frame size ({current_frame_width},{current_frame_height})")
    print(f"parent Frame Width: {parent_width} pixels Height: {parent_height} pixels")
    # 最大不可 超出frame最大高度 最少暴漏出10个像素点
    x = x if parent_width > x else parent_width - 10
    y = y if parent_height > y else parent_height - 10
    x = -current_frame_width + 10 if x <= -current_frame_width + 10 else x
    y = -current_frame_height + 10 if y <= -current_frame_height + 10 else y
    print(f"move to ({x},{y})")

    t2.place(x=x, y=y)




root = tk.Tk()
root.title("Mouse Drawing")

canvas = tk.Canvas(root, width=400, height=300, bg='gray')
canvas.pack()

t1 = tk.Frame(canvas, width=50, height=50)
t2 = tk.Frame(canvas, width=50, height=50, bg="black")
t1.place(x=50, y=50)
t2.place(x=200, y=50)

t1_xy = (50, 50)
t2_xy = (200, 50)

# 绑定鼠标事件
t2.bind("<ButtonPress-1>", on_mouse_down)
t2.bind("<ButtonRelease-1>", on_mouse_up)
t2.bind("<B1-Motion>", on_mouse_move)


root.mainloop()